package controller

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
)

func DownloadHandler(c *gin.Context) {
	log.Println("Handling download request for:", c.Param("filename"))
	filename := c.Param("filename")
	filePath := filepath.Join(uploadPath, filename)

	// Clean the file path to prevent directory traversal attacks
	cleanFilePath := filepath.Clean(filePath)

	// Ensure the cleaned file path is still within the uploads directory
	if !filepath.HasPrefix(cleanFilePath, uploadPath) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的文件路径"})
		return
	}

	file, err := os.Open(cleanFilePath)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "文件未找到"})
		return
	}
	defer file.Close()

	fileInfo, err := file.Stat()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "文件状态错误"})
		return
	}

	c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileInfo.Name()))
	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))

	io.Copy(c.Writer, file)
}
